import { computed, reactive } from 'vue';
import { BaseType } from '../index';


export function useSelectTable(multiple: boolean = true) {
  const serverMap = reactive(new Map())
  const select = reactive<any>({
    selectedRowKeys: [],
    showCheckedAll: true,
    type: multiple ? 'checkbox' : 'radio',
  })

  const selectedMap = reactive(new Map())
  const onChange = (keys: BaseType[]): void => {
    keys.forEach((key: BaseType): void => {
      const row = serverMap.get(key)
      if (row) {
        selectedMap.set(key, row)
      }
    })
    for (const key of selectedMap.keys()) {
      if (!keys.includes(key)) {
        selectedMap.delete(key)
      }
    }
    select.selectedRowKeys = keys
  }

  const onClear = (): void => {
    select.selectedRowKeys = []
    selectedMap.clear()
  }
  const disabled = computed(() => !selectedMap.size)
  return {
    disabled,
    onClear,
    select,
    serverMap,
    selectedMap,
    onChange,
  }
}
